package com.epam.task.web.dao;

import com.epam.task.web.entity.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * User: zhunusbekova.arailym
 */
public class DAO {
    private static final Logger logger = LoggerFactory.getLogger(DAO.class);

    public static final List<Order> getAllOrders() {
        List<Order> ret = null;
        try {
            SqlMapClient sqlMap = SqlMapUtil.getInstance().getSqlClient();
            ret = (List<Order>) sqlMap.queryForList("getAllOrders");
        } catch (Exception e) {
            logger.error("Error retrieving orders", e);
        }
        return ret;
    }

    public static void insertInstrument(Order curr) {
        try {
            SqlMapClient sqlMap = SqlMapUtil.getInstance().getSqlClient();
            sqlMap.insert("insertOrder", curr);
        } catch (Exception e) {
            logger.error("Could not insert order", e);
        }
    }

    public static void updateInstrument(Order curr) {
        try {
            SqlMapClient sqlMap = SqlMapUtil.getInstance().getSqlClient();
            sqlMap.update("updateOrder", curr);
        } catch (Exception e) {
            logger.error("Could not update order", e);
        }
    }

    public static void deleteInstrument(Order instr) {
        SqlMapClient sqlMap = SqlMapUtil.getInstance().getSqlClient();
        try {
            sqlMap.startTransaction();
            sqlMap.delete("deleteOrderFromStrat", instr.getId());
            sqlMap.delete("deleteOrderBars", instr.getId());
            sqlMap.delete("deleteOrderBarseries", instr.getId());
            sqlMap.delete("deleteOrder", instr.getId());
            sqlMap.commitTransaction();
        } catch (Exception e) {
            logger.error("Could not delete order", e);
        } finally {
            try {
                sqlMap.endTransaction();
            } catch (SQLException e) {
            }
        }
    }

}
